#import sys 
#reload(sys)
#sys.setdefaultencoding('utf8')
import win32serviceutil   
import win32service   
import win32event
import coop
import os,time,sys
  
class CoopService(win32serviceutil.ServiceFramework):   
# """ 
# Usage: 'CoopService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]' 
# Options for 'install' and 'update' commands only: 
 # --username domain\username : The Username the service is to run under 
 # --password password : The password for the username 
 # --startup [manual|auto|disabled|delayed] : How the service starts, default = manual 
 # --interactive : Allow the service to interact with the desktop. 
 # --perfmonini file: .ini file to use for registering performance monitor data 
 # --perfmondll file: .dll file to use when querying the service for 
   # performance data, default = perfmondata.dll 
# Options for 'start' and 'stop' commands only: 
 # --wait seconds: Wait for the service to actually start or stop. 
				 # If you specify --wait with the 'stop' option, the service 
				 # and all dependent services will be stopped, each waiting 
				 # the specified period. 
# """  
    #服务名  
    _svc_name_ = "CoopService"  
    #服务显示名称  
    _svc_display_name_ = "Coop Service"  
    #服务描述  
    _svc_description_ = "Coop service."  
  
    def __init__(self, args):   
        win32serviceutil.ServiceFramework.__init__(self, args)   
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)  
        self.logger = self._getLogger()  
        self.isAlive = True  
        self.coop = coop.Coop()
         
    def _getLogger(self):  
        import logging  
        import os  
        import inspect  
          
        logger = logging.getLogger('[CoopService]')  
          
        this_file = inspect.getfile(inspect.currentframe())  
        dirpath = os.path.abspath(os.path.dirname(this_file))  
        handler = logging.FileHandler(os.path.join(dirpath, "coop.log"))  
          
        formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')  
        handler.setFormatter(formatter)  
          
        logger.addHandler(handler)  
        logger.setLevel(logging.INFO)  
          
        return logger  
  
    def SvcDoRun(self):  
        self.logger.error("svc do run....")   
        while self.isAlive:
            self.coop.run() 
            time.sleep(1)
        # 等待服务被停止   
        #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)   
              
    def SvcStop(self):   
        # 先告诉SCM停止这个过程   
        self.logger.error("svc do stop....")  
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)   
        # 设置事件   
        win32event.SetEvent(self.hWaitStop)   
        self.isAlive = False  
        self.coop.terminate() 
  
if __name__=='__main__':
    if len(sys.argv) == 1:
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(CoopService)
            servicemanager.Initialize('CoopService', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(CoopService)

